<script setup lang="ts">
import { getIndustryListAPI } from '@/apis/card';
import { createEnterpriseAPI, uploadAPI } from '@/apis/common';
import type { EnterpriseParams, Industry } from '@/types/enterprise';
import { SuccessFilled, Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: undefined // 营业执照id
}) 

// 添加企业表单校验
const addRules=ref<FormRules<EnterpriseParams>>({
   name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
   legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
   contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
   contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
   industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
  
})
const  submitLoading=ref(false)
const   router=useRouter()
// 表单整体校验
const  formRef=ref<FormInstance>()
// 确定提交校验
const onSubmit=async()=>{
  try{
    submitLoading.value=true
    await formRef.value?.validate()
// 提交表单表单数据到后端
    await createEnterpriseAPI(addForm.value)
//请提示
    ElMessage.success('添加成功')
    // 返回到上一页
    router.back()
  }finally{
    submitLoading.value=false
  }

}

//重置表单
const onReset=()=>{
  formRef.value?.resetFields()
}

// 获取行业列表
const industryList=ref<Industry[]>([])
const getindustryList=async()=>{
  const  res=await getIndustryListAPI()
  // console.log(res);
  industryList.value=res.data
 
}

getindustryList()
// 接收
const filelist=ref<UploadUserFile[]>([])
// 上传图片
const   onUploadRequest = async (options:UploadRequestOptions) => {
  const data=new FormData()
  data.append('file',options.file)
  data.append('type','businessLicense')
  const res=await uploadAPI(data)
  // 保存营业执照id
  addForm.value.businessLicenseUrl=res.data.url
  addForm.value.businessLicenseId=res.data.id
  // 主动触发校验
  formRef.value?.validateField('businessLicenseUrl')
  // 将图片返回出去
  return res.data.url
  
  }

  const  removeUpload=()=>{
// 主动清除营业指导 id
    addForm.value.businessLicenseUrl=''
    addForm.value.businessLicenseId=undefined
    // 触发校验，提醒用户
    formRef.value?.validateField('businessLicenseUrl')
  }

  // 图片大小类型判断
  const beforeupload=(rawFile: UploadRawFile)=>{
     if(rawFile.size>5*1024*1024){
      ElMessage.error('图片大小不能超过5M')
      return false
     }else if(!['image/jpeg','image/png'].includes(rawFile.type)){
      ElMessage.success('图片格式不正确')
      return false
     }
     return true
    
  }
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form :model="addForm" :rules="addRules"  ref="formRef" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" >          
                <el-option
                v-for="item in industryList"
                :key="item.industryCode"
                :label="item.industryName"
                :value="item.industryCode"
                
                 ></el-option>
                
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber"  maxlength="11"/>
            </el-form-item>
            <el-form-item label="营业执照"  prop="businessLicenseUrl">
              <!-- 上传图片    图片上传属性                     图片显示预览    图片数量限制       图片上传数据绑定          上传文件之前的钩子，校验文件大小和格式       js原生自带校验图片格式的                    -->
            <el-upload  :http-request="onUploadRequest" list-type="picture"  :limit="1"  v-model:file-list="filelist"    :before-upload="beforeupload"      accept="..png, .jpg, .jpeg"     @remove="removeUpload"
            >
           <!-- if判断上传没图片  -->
              <el-button  color="#626aef" v-if="filelist.length===0"><el-icon><Upload /></el-icon> 上传</el-button>
                <el-button color="#4bc9b0" v-else> <el-icon><SuccessFilled /></el-icon>已上传</el-button>
              <template #tip>
                  <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </template>
            
          </el-upload>
               
            </el-form-item>
          </el-form>
          {{ addForm }}
        </div>
   
      </div>
     
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button  @click="onReset">重置</el-button>
        <!--                            提交中禁用按钮 :loading                        -->
        <el-button type="primary" link @click="onSubmit"   :loading="submitLoading"> 确定</el-button>
      </div>
    </footer>

  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>